/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: IMU_Dummy.cpp,v 1.6 2009-06-29 12:57:29 morsko Exp $
 *
 * \file
 * \brief Dummy implementation for IMU Server interface.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 * This implementation can act as an example / codebase for any
 * IMU server based module implementation. This code follows a
 * pseudogood coding style, and also provides a basic parameter
 * parser that can be directly used with slight modifications.
 * 
 */
#include <stdio.h>
#include <stdlib.h>
#include "owndebug.h"
#include "IMUServer.hpp"
#include "binbag.h"

//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
static int verbose = 1;
//*****************************************************************************
using namespace MaCI;
//*****************************************************************************
void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tIMU_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-G name]\t\t\tUse 'name' as MaCIGroup for this service\n");
  fprintf(stderr,"  [-I name]\t\t\tUse 'name' as Instancename for this service\n");

  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************
int main(int argc, char *argv[]) 
{
 // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 50002;
  std::string gimnetName = "";
  std::string maciGroupName;
  std::string interfaceInstanceName = "Dummy";

  // Objects
  bool run = true;
  gimi::GIMI g;
  MaCI::MaCICtrl::CMaCICtrlServer mcs(&g);
  MaCI::IMU::CIMUServer imuS(&mcs, 0); 
  
  MaCI::IMU::TEventTypes types;
  types.continuousTypes = 0;//1<<MaCI::IMU::KTypeAcceleration3d | 1<<MaCI::IMU::KTypeAngle3d | 1<<MaCI::IMU::KTypeAngularVelocity3d;
  dPrint(1,"Setting event types");
  imuS.SetEventTypes(types);
  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  debugSetLogFilename("IMU_Dummy.log");

  // Greet
  fprintf(stderr,
	  "\nIMU_Dummy - MaCI IMU Interface implementation for Dummy - v0.00003\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "I:G:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      maciGroupName = optarg;
      dPrint(3,"Using MaCIGroupName '%s'", optarg);
      break;

    case 'I':
      interfaceInstanceName = optarg;
      dPrint(3,"Using InterfaceInstance Name '%s'", optarg);
      break;
      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  mcs.SetGroupName(maciGroupName);
  imuS.SetInterfaceInstanceName(interfaceInstanceName);
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    MaCI::EMaCIError e;
    if ( (e = imuS.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open SpeedCtrlServer instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {
      ////// Execute test section ///////

      // Run as long as 'run' is set.
      while (run) {  
	using namespace MaCI::IMU;

	// Construct Data element
	MaCI::IMU::CIMUData imudata;
        TReplyInfo rInfo;
	gim::binbag::CBinBag bb;
	// Now, sit back and wait for command to arrive (for 1000ms)
        e = imuS.WaitCommand(imudata,rInfo, 1000);

	// Got command? (No timeout or error)
        if (e == MaCI::KMaCIOK) {
          const TCommand *cmd = imudata.GetCommand();
	  assert(cmd != NULL);
	  // Switch based on command type
	  switch(cmd->cmd) {
          case KCommandGetAcceleration3d :{
            dPrint(1,"GOT COMMAND GET ACCELERATION 3D");
            ownSleep_ms(100);
            CIMUData imuReply;
            imuReply.EncodeTo(&bb);
            imuReply.SetCommand(TCommand(KCommandGetAcceleration3dReply));
            imuReply.SetAcceleration3d(TAcceleration3d(1.1,1.2,1.3));
            const MaCI::Common::TTimestamp tstamp;
            imuReply.SetTimestamp(tstamp);
            e = imuS.SendReply(imuReply,rInfo);
            if(e != MaCI::KMaCIOK){
              dPrint(1,"WARNING: Reply sending failed!");
            }
            break;
          }
          case   KCommandGetAngularVelocity3d:{
            dPrint(1,"GOT COMMAND GET ANGULAR VELOCITY 3D");
            ownSleep_ms(100);
            CIMUData imuReply;
            imuReply.EncodeTo(&bb);
            imuReply.SetCommand(TCommand(KCommandGetAngularVelocity3dReply));
            imuReply.SetAngularVelocity3d(TAngularVelocity3d(1.2,2.2,2.3));
            const MaCI::Common::TTimestamp tstamp;
            imuReply.SetTimestamp(tstamp);
            e = imuS.SendReply(imuReply,rInfo);
            if(e != MaCI::KMaCIOK){
              dPrint(1,"WARNING: Reply sending failed!");
            }
            break;
          }        
          case   KCommandGetAngle3d:{
            dPrint(1,"GOT COMMAND GET ANGLE 3D"); 
            ownSleep_ms(100);
            CIMUData imuReply;
            imuReply.EncodeTo(&bb);
            imuReply.SetCommand(TCommand(KCommandGetAngle3dReply));
            imuReply.SetAngle3d(TAngle3d(2.2,1.1,1.13));
            const MaCI::Common::TTimestamp tstamp;
            imuReply.SetTimestamp(tstamp);
            e = imuS.SendReply(imuReply,rInfo);
            if(e != MaCI::KMaCIOK){
              dPrint(1,"WARNING: Reply sending failed!");
            }
            break;
          }        
          case   KCommandGetQuaternion:{
            dPrint(1,"GOT COMMAND GET QUATERNION");
            ownSleep_ms(100);
            CIMUData imuReply;
            imuReply.EncodeTo(&bb);
            imuReply.SetCommand(TCommand(KCommandGetQuaternionReply));
            imuReply.SetQuaternion(TQuaternion(1.2,1.1,1.2,1.3));
            const MaCI::Common::TTimestamp tstamp;
            imuReply.SetTimestamp(tstamp);
            e = imuS.SendReply(imuReply,rInfo);
            if(e != MaCI::KMaCIOK){
              dPrint(1,"WARNING: Reply sending failed!");
            }
            break;
          }        
          case   KCommandGetOrientationMatrix:{
            dPrint(1,"GOT COMMAND GET ORIENTATION MATRIX");
            ownSleep_ms(100);
            CIMUData imuReply;
            imuReply.EncodeTo(&bb);
            imuReply.SetCommand(TCommand(KCommandGetOrientationMatrixReply));
            imuReply.SetOrientationMatrix(TOrientationMatrix(1.1, 
                                                             1.2,
                                                             1.3,
                                                             2.2,
                                                             3.3,
                                                             3.4,
                                                             5.5,
                                                             2.1,
                                                             4.4));
            const MaCI::Common::TTimestamp tstamp;
            imuReply.SetTimestamp(tstamp);
            e = imuS.SendReply(imuReply,rInfo);

            if(e != MaCI::KMaCIOK){
              dPrint(1,"WARNING: Reply sending failed!");
            }
           
            break;
          }  
          default:{
            dPrint(1,"No implementation for command %d!", cmd->cmd);
	    break;
	  }
	  }

        } else if (e == MaCI::KMaCITimeout) {
          // No, timeout waiting for command. Print and wait again.
          dPrint(8,"Timeout waiting for Command");
          
        } else {
          // Quck? Some error occured? Print it, sleep an extra second and try again.
          dPrint(1,"Failed to WaitCommand()! (%s)",
                 GetErrorStr(e).c_str());
          ownSleep_ms(1000);
        }
      }
    }
  }
  
  return 0;
}
